﻿#region Using directives

using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using InvoiceChecking.Data;
using InvoiceChecking.Entities;
using InvoiceChecking.Web.UI;

#endregion

public partial class Admin_SendInvoice : Page
{
    private VList<AllInvoice> _allInvoices;

    protected void Page_Load(object sender, EventArgs e)
    {
        FormUtilBase.SetPageIndex(GridView1, "page");
        if (!IsPostBack)
        {
            BindGrid();
            PreRenderComplete += Admin_SendInvoice_PreRenderComplete;
        }
        ScriptManager1.RegisterPostBackControl(btn_Export);
    }

    void Admin_SendInvoice_PreRenderComplete(object sender, EventArgs e)
    {
        ddl_Company.Items.Insert(1, new ListItem("All", "All"));
    }


    private void BindGrid()
    {
        if (!string.IsNullOrEmpty(ddl_Company.SelectedValue))
        {
            if (ddl_Company.SelectedValue == "All")
            {
                btn_Preview.Enabled = false;
                btn_Send.Enabled = false;
                btn_Receive.Enabled = false;
                const string whereClause = @"( PaymentMode IN 
                                            ( SELECT   KIND_PMENT
                                            FROM     dbo.AB_ACCOUNT_CODE
                                            WHERE    KIND_PMENT_DESC = 'CCP' )
                                        AND PaymentModeRevised = ''
                                        OR PaymentModeRevised IN 
                                            ( SELECT KIND_PMENT
                                             FROM   dbo.AB_ACCOUNT_CODE
                                             WHERE  KIND_PMENT_DESC = 'CCP' ))
                                        AND SendDate IS NULL
                                        AND Received = 1 ";
                int count;
                GridView1.DataSource = DataRepository.AllInvoiceProvider.GetPaged(whereClause, "VatInvoiceNumber DESC", 0, 100,
                                                                         out count);
                GridView1.DataBind();
            }
            else
            {
                btn_Preview.Enabled = true;
                btn_Send.Enabled = true;
                btn_Receive.Enabled = true;
                GetInvoices();
                VList<AllInvoice> prepareToSend = (VList<AllInvoice>)Session[ddl_Company.SelectedValue] ??
                                                  new VList<AllInvoice>();
                foreach (AllInvoice invoice in prepareToSend)
                {
                    AllInvoice invoice1 = invoice;
                    AllInvoice invoiceResult =
                        _allInvoices.Find(targetinvoice => targetinvoice.VatInvoiceNumber == invoice1.VatInvoiceNumber);
                    _allInvoices.Remove(invoiceResult);
                }
                GridView1.DataSource = _allInvoices;
                GridView1.DataBind();

                grv_PrepareToSend.DataSource = prepareToSend;
                grv_PrepareToSend.DataBind();
                tb_InvoiceNumber.Focus();
            }
        }
    }

    private void GetInvoices()
    {
        string whereClause =
            string.Format(
                "((PaymentMode = '{0}' AND PaymentModeRevised='') OR PaymentModeRevised='{0}') AND SendDate IS NULL AND Received=1",
                ddl_Company.SelectedValue);
        int count;
        _allInvoices = DataRepository.AllInvoiceProvider.GetPaged(whereClause, "VatInvoiceNumber DESC", 0, 100,
                                                                  out count);
    }

    protected void btn_Receive_Click(object sender, EventArgs e)
    {
        if (tb_InvoiceNumber.Text.Length >= 10)
        {
            string invoiceNumber = tb_InvoiceNumber.Text.Substring(0, 10);
            if (_allInvoices == null)
                GetInvoices();
            AllInvoice allInvoice = _allInvoices.Find(invoice => invoice.VatInvoiceNumber == invoiceNumber);

            if (allInvoice != null)
            {
                VList<AllInvoice> prepareToSend = (VList<AllInvoice>)Session[ddl_Company.SelectedValue] ??
                                                  new VList<AllInvoice>();
                if (prepareToSend.Find(invoice => invoice.VatInvoiceNumber == invoiceNumber) == null)
                    prepareToSend.Add(allInvoice);
                tb_InvoiceNumber.Text = "";
                Session[ddl_Company.SelectedValue] = prepareToSend;
                BindGrid();
            }
        }
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Add")
        {
            string invoiceNumber = e.CommandArgument.ToString();
            tb_InvoiceNumber.Text = invoiceNumber;
            btn_Receive_Click(null, null);
        }
        else if (e.CommandName == "Remove")
        {
            string invoiceNumber = e.CommandArgument.ToString();
            VList<AllInvoice> prepareToSend = (VList<AllInvoice>)Session[ddl_Company.SelectedValue] ??
                                              new VList<AllInvoice>();
            AllInvoice targetInvoice = prepareToSend.Find(invoice => invoice.VatInvoiceNumber == invoiceNumber);
            prepareToSend.Remove(targetInvoice);
            Session[ddl_Company.SelectedValue] = prepareToSend;
            BindGrid();
        }
    }

    protected void ddl_Company_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindGrid();
    }

    protected void btn_Preview_Click(object sender, EventArgs e)
    {
        Response.Redirect("ReportSendInvoice.aspx?CompanyCode=" + ddl_Company.SelectedValue, true);
    }

    protected void btn_Send_Click(object sender, EventArgs e)
    {
        Response.Redirect("ReportSendInvoice.aspx?CompanyCode=" + ddl_Company.SelectedValue + "&Send=True", true);
    }

    protected void btn_Export_Click(object sender, EventArgs eventArgs)
    {
        BindGrid();
        ExportToExcel();
    }
    protected void ExportToExcel()
    {
        Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition", "attachment;filename=NotSendInvoices.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];

            //Apply text style to each Row
            foreach (TableCell cell in row.Cells)
            {
                cell.Attributes.Add("class", "textmode");
            }
        }
        GridView1.RenderControl(hw);
        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }
}